<template>
  <div class="container">
    <Breadcrumb :items="['menu.project', 'menu.project.search']" />
    <a-card class="general-card" :title="$t('menu.project.search')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="number" :label="$t('project.name')">
                  <a-input
                    v-model="formModel.searchKey"
                    :placeholder="$t('projectTable.placeholder.project.name')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="createdTime"
                  :label="$t('projectTable.form.createdTime')"
                >
                  <a-range-picker
                    v-model="formModel.createTime"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="updateTime"
                  :label="$t('projectTable.form.updateTime')"
                >
                  <a-range-picker
                    v-model="formModel.updateTime"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="status"
                  :label="$t('projectTable.form.status')"
                >
                  <a-select
                    v-model="formModel.enabled"
                    allow-clear
                    :options="statusOptions"
                    :placeholder="$t('projectTable.form.selectDefault')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('projectTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('projectTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px" :gutter="16">
        <a-col>
          <a-space>
            <a-button type="primary" @click="handleEdit(true, undefined)">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('projectTable.operation.create') }}
            </a-button>
            <a-button type="outline" @click="syncProjects">
              <template #icon>
                <icon-sync />
              </template>
              {{ $t('consul.form.sync') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column
            :title="$t('project.name')"
            data-index="projectName"
          />
          <a-table-column :title="$t('order.index')" data-index="orderIndex" />
          <a-table-column :title="$t('projectTable.columns.createdTime')">
            <template #cell="{ record }">
              {{ formatDate(record.createTime * 1000) }}
            </template>
          </a-table-column>
          <a-table-column :title="$t('projectTable.columns.updateTime')">
            <template #cell="{ record }">
              {{ formatDate(record.updateTime * 1000) }}
            </template>
          </a-table-column>
          <a-table-column
            :title="$t('projectTable.columns.status')"
            data-index="status"
          >
            <template #cell="{ record }">
              <a-tag :color="record.enabled ? 'blue' : 'orange'">
                <template #icon>
                  <icon-check v-if="record.enabled" />
                  <icon-close v-else />
                </template>
                {{
                  $t(`${record.enabled ? 'radio.enabled' : 'radio.disabled'}`)
                }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column
            :title="$t('projectTable.columns.operations')"
            data-index="operations"
          >
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  :status="record.enabled ? 'warning' : 'success'"
                  size="small"
                  @click="patchProjectEnabled(record.id, !record.enabled)"
                >
                  {{
                    $t(`${record.enabled ? 'radio.disabled' : 'radio.enabled'}`)
                  }}
                </a-button>
                <a-button
                  type="outline"
                  size="small"
                  @click="
                    handleEdit(false, {
                      projectName: record.projectName,
                      id: record.id,
                      orderIndex: record.orderIndex,
                    })
                  "
                >
                  {{ $t('projectTable.columns.operations.edit') }}
                </a-button>
                <a-button
                  type="primary"
                  size="small"
                  @click="toRoutePageSearch(record.id)"
                >
                  {{ $t('projectTable.columns.operations.set.route') }}
                </a-button>
                <a-button
                  type="primary"
                  size="small"
                  status="danger"
                  @click="handleDel(record.id)"
                >
                  {{ $t('projectTable.columns.operations.del') }}
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="visible"
      :title="
        $t(
          `${
            isCreate
              ? 'projectTable.operation.create.projetct'
              : 'projectTable.operation.update.projetct'
          }`
        )
      "
      :mask-closable="false"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form :model="form">
        <a-form-item field="projectName" :label="$t('project.name')">
          <a-input v-model="form.projectName" />
        </a-form-item>
        <a-form-item field="orderIndex" :label="$t('order.index')">
          <a-input-number v-model="form.orderIndex" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {
    getPageProject,
    patchProject,
    insertProject,
    updateProject,
    EditProjectModel,
    ProjectModel,
    PageQueryProjectParams,
    deleteProject,
  } from '@/api/project';
  import { getAllSelect } from '@/api/dictionary';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  import { useRouteStore } from '@/store';

  const consulSettingKeyOptions = ref<SelectOptionData[]>([]);
  const consulDCOptions = ref<SelectOptionData[]>([]);
  const initSelect = async () => {
    const { data } = await getAllSelect();
    consulSettingKeyOptions.value = data.consulSettingKey;
    consulDCOptions.value = data.consulDC;
  };

  initSelect();

  const router = useRouter();
  const visible = ref(false);
  const isCreate = ref(true);
  const form = ref<EditProjectModel>({
    projectName: '',
    id: 0,
    orderIndex: 1,
  });

  const handleCancel = () => {
    visible.value = false;
  };
  const handleOk = async () => {
    visible.value = false;
    if (isCreate.value) {
      await insertProject(form.value);
    } else {
      await updateProject(form.value);
    }
    const msg = t('detailForm.submitSuccess');
    Message.success({
      content: msg,
      duration: 5 * 1000,
    });
    fetchData();
  };
  const handleEdit = (
    useCreate: boolean,
    editProjectParams: EditProjectModel | undefined
  ) => {
    if (useCreate) {
      form.value = { projectName: '', id: 0, orderIndex: 1 };
    } else {
      form.value = editProjectParams as EditProjectModel;
    }
    visible.value = true;
    isCreate.value = useCreate;
  };
  const handleDel = (projectId: number) => {
    Modal.warning({
      title: 'Warning Notification',
      content:
        'This is a warning description which directly indicates a warning that might need attention.',
      okText: t('confirm'),
      cancelText: t('cancel'),
      hideCancel: false,
      onOk: () => {
        deleteProject(projectId);
        const msg = t('detailForm.submitSuccess');
        Message.success({
          content: msg,
          duration: 5 * 1000,
        });
        fetchData();
      },
    });
  };
  const generateFormModel = () => {
    return {
      searchKey: '',
      enabled: undefined,
      orderIndex: undefined,
      createTime: [],
      updateTime: [],
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<ProjectModel[]>([]);
  const formModel = ref(generateFormModel());
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('radio.enabled'),
      value: 1,
    },
    {
      label: t('radio.disabled'),
      value: 0,
    },
  ]);
  const fetchData = async (
    params: PageQueryProjectParams = {
      current: 1,
      pageSize: 10,
      searchKey: '',
      enabled: undefined,
      orderIndex: undefined,
      createTime: [],
      updateTime: [],
    }
  ) => {
    setLoading(true);
    try {
      const { data } = await getPageProject(params);
      renderData.value = data.items;
      pagination.current = params.current;
      pagination.total = data.totalCount;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    basePagination.current = 1;
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PageQueryProjectParams);
  };

  const syncProjects = async () => {
    router.push({
      name: 'SysnRoute',
    });
  };

  const onPageChange = (current: number) => {
    basePagination.current = current;
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PageQueryProjectParams);
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const patchProjectEnabled = async (projectId: number, enabled: boolean) => {
    await patchProject(projectId, enabled);
    const msg = t('detailForm.submitSuccess');
    Message.success({
      content: msg,
      duration: 5 * 1000,
    });
    fetchData();
  };

  const formatDate = (value: any) => {
    const date = new Date(value);
    const y = date.getFullYear();
    const MM = date.getMonth() + 1;
    const MMstr = MM < 10 ? `0${MM}` : MM;
    const d = date.getDate();
    const dstr = d < 10 ? `0${d}` : d;
    const h = date.getHours();
    const hstr = h < 10 ? `0${h}` : h;
    const m = date.getMinutes();
    const mstr = m < 10 ? `0${m}` : m;
    const s = date.getSeconds();
    const sstr = s < 10 ? `0${s}` : s;
    return `${y}-${MMstr}-${dstr} ${hstr}:${mstr}:${sstr}`;
  };

  const toRoutePageSearch = (projectId: number) => {
    const routeStore = useRouteStore();
    routeStore.toggleProjectId(projectId);
    router.push({
      name: 'SearchRoute',
    });
  };
</script>

<script lang="ts">
  export default {
    name: 'SearchProject',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
